<?

error_reporting(E_ALL);

require_once 'define.inc';
require_once 'helpers.inc';
require_once "PageClass.inc";

class Project
{
    /**
     * A Project
     *
     */

    protected $_row = array();
    protected $_projectid = null;

    public function Project($projectid) {
        global $DpDb;
        $this->_projectid = $projectid;

        $sql = $this->sqlProject() ;
        $this->_row = $DpDb->SqlOneRow($sql);
    }

    public function AmazonLink() {
        $s = $this->AuthorsName() ;
        $akey = str_replace(" ", "%20", $s ) ;

        $url = "http://webservices.amazon.com/onca/xml"
        ."?Service=AWSECommerceService"
        ."&AWSAccessKeyId=[Your Access Key ID Here]"
        ."&Operation=ItemSearch"
        ."&SearchIndex=Books"
        ."&Author=".$akey;

        return $url ;
    }

/*
    public function UserTasks()
    {
        static $pgs ;

        if(! isset($pgs ) ) {
            require_once 'PageTaskClass.inc';
            $pgs = new UserTasks($this->ProjectId());
        }
        return $pgs;
    }
*/

    public function Exists() {
        return !empty($this->_row);
    }

    public function RequestPageTask($projectid, $pagecode, $taskcode) {
        global $DpDb;

        $sql = "
            SELECT
                pp.*
            FROM
                pages AS pp
            LEFT JOIN
                pagetasks AS pt
            ON
                pp.projectid = pt.projectid
                AND pp.pagecode = pt.pagecode
            WHERE
                pp.projectid = '$projectid'
                AND pp.pagecode = '$pagecode'
                AND pt.taskcode = '$taskcode'
                AND pt.sequence = $seq";

        // echo "$sql<br />";
        return $DpDb->SqlOneRow($sql);
    }

    public function SavedCount($taskcode) {
        static $icount ;
        global $DpDb;
        if( ! isset( $icount ) ) {
            $sql = "SELECT COUNT(1) FROM pagetasks
                    WHERE projectid = '$this->_projectid'
                        AND taskcode = '$taskcode'
                        AND NOT completiontime IS NULL";
            $icount = $DpDb->SqlOneValue($sql) ;
        }
        return $icount;
    }

    public function SetTasks( $atasks ) {
        global $DpDb;
        global $Context;

        $tlist = "" ;
        foreach( $atasks as $t )
        {
            $tlist .= ",\n'$t'" ;
        }
        $tlist = substr( $tlist, 1 ) ;

        $sql = "DELETE FROM projecttasks
                WHERE projectid = '$this->_projectid'";
        $i = $DpDb->SqlExecute($sql) ;
            
        if( count( $atasks ) > 0 ) {
            $sql = "INSERT INTO projecttasks
                    (
                        projectid,
                        taskcode, 
                        sequencenumber
                    )
                    SELECT
                        '$this->_projectid',
                        t.taskcode,
                        t.sequencenumber
                    FROM
                        projects AS p,
                        tasks AS t
                    WHERE
                        t.taskcode IN
                        ( $tlist )
                        AND p.projectid = '$this->_projectid'";
            $i = $DpDb->SqlExecute( $sql ) ;
            assert( $i > 0 ) ;
            foreach($atasks as $t) {
                $Context->LogEvent( "ADDPROJTASK",
                                    $this->ProjectId(),
                                    null,
                                    $t) ;
            }
        }
    }

    public function ProjectTasks() {
        global $DpDb;
        static $_tasks ;
        if(!isset($_tasks))
        {
            $_tasks = array() ;
            $sql = "SELECT DISTINCT pt.taskcode
                    FROM projecttasks AS pt
                    JOIN tasks AS t ON pt.taskcode = t.taskcode
                    WHERE projectid = '$this->_projectid'
                    AND t.isscheduled != 0";
        // echo "$sql<br />";
            foreach( $DpDb->SqlRows($sql) as $row ) {
                $_tasks[$row[0]] = $row[0];
            }
        }
        return $_tasks ;
    }

    public function AvailableTasks() {
        static $_tasks ;

        if( empty( $_tasks ) ) 
        {
            global $DpDb ;
            global $User ;

            $username = $User->UserName() ;
            $projectid = $this->ProjectId() ;
            $_tasks = array() ;

            /*
                Task is available if:

                    1. user is "qualified" because
                        a. task.tasktype = 'A' (for "All"), or
                        b. task's qualcode is matched by a user qualcode
                       
                    AND
                    2. there is work to do because
                        a. user has a task checked out,
                        b. user has a task completed and no task has been checked out since,
                        c. a task exists which is not checked out
                            and no incomplete lower sequence task is incomplete,
                            and no immediately preceding task done by the same user
            */
            $sql = "SELECT DISTINCT
                        '$projectid' projectid,
                        t.taskcode 
                    FROM 
                        tasks t
                    JOIN
                        pagetasks pt
                    ON
                        t.taskcode = pt.taskcode
                        AND pt.checkouttime IS NULL

                    LEFT JOIN
                        userquals uq
                    ON
                        t.qualcode = uq.qualcode
                        AND uq.username = '$username'

                    LEFT JOIN
                        pagetasks prevpt
                    ON
                        pt.projectid = prevpt.projectid
                        AND pt.pagecode = prevpt.pagecode
                        AND pt.sequencenumber > prevpt.sequencenumber

                    LEFT JOIN
                        pagetasks prevcheck
                    ON
                        prevpt.projectid = prevcheck.projectid
                        AND prevpt.pagecode = prevcheck.pagecode
                        AND prevpt.sequencenumber < prevcheck.sequencenumber
                        AND pt.sequencenumber > prevcheck.sequencenumber
                        
                    WHERE
                        pt.projectid =  '$projectid'
                        AND
                        (
                            tasktype = 'A'
                            OR NOT uq.userqualid IS NULL
                            AND
                            (
                                prevpt.pagetaskid IS NULL
                                OR
                                (
                                    NOT prevpt.completiontime IS NULL
                                    AND prevcheck.pagetaskid IS NULL
                                )
                            )
                        )

                    ORDER BY
                        t.sequencenumber";

            // die( PrettySql( $sql ) ) ;

            $_tasks = $DpDb->SqlObjects($sql) ;
        }
        return $_tasks;
    }

    public function IsProjectTask($taskcode) {
        $t = $this->ProjectTasks();
        $j = isset($t[$taskcode])?"yes":"no";
        return isset( $t[$taskcode] ) ;
    }

    private function _proj_unzip_dir() {
        return $this->ProjectPath() . '/ziptemp';
    }

    public function SetDefaultPageTasks() {
        global $DpDb;

        $sql = "CALL SetDefaultProjectTasks( '$this->_projectid' )";
        $DpDb->SqlExecute($sql);
        $this->SetPageTasks();
    }

    public function SetPageTasks() {
        global $DpDb;
        global $Context;

        $sql = "INSERT INTO pagetasks
                (
                    projectid,
                    pagecode,
                    sequencenumber,
                    taskcode
                )
                SELECT
                    pt.projectid,
                    pp.pagecode,
                    pt.sequencenumber,
                    pt.taskcode
                FROM
                    projecttasks AS pt
                JOIN
                    pages AS pp
                ON
                    pt.projectid = pp.projectid
                WHERE
                    pt.projectid = '{$this->ProjectId()}'
                AND NOT EXISTS
                (	SELECT pagetaskid
                    FROM pagetasks
                    WHERE projectid = pt.projectid
                        AND pagecode = pp.pagecode
                        AND taskcode = pt.taskcode
                )\n";
        // die(PrettySql($sql));

        $DpDb->SqlExecute($sql);
    }

    public function TaskCodes() {
        global $DpDb ;
        $sql = "SELECT DISTINCT pt.taskcode
                FROM pagetasks AS pt
                JOIN tasks AS t ON pt.taskcode = t.taskcode
                WHERE projectid = '$this->_projectid'
                ORDER BY t.sequencenumber";
        // echo "$sql<br />";
        return $DpDb->SqlRows( $sql ) ;
    }

    // taskcode, PgTaskCount
    public function PageTaskCounts() {
        global $DpDb;

        $sql_select = "
            SELECT
                pp.pagecode";
        
        $sql_from = "
            FROM
                pages AS pp" ;

        $rows = $this->TaskCodes() ;
        foreach( $rows as $row )
        {
            $code = $row[0] ;
            $sql_select .= ",
                {$code}.username AS {$code}_username,
                {$code}.checkouttime AS {$code}_checkouttime,
                {$code}.completiontime AS {$code}_completiontime";

            $sql_from .= "
                LEFT JOIN pagetasks AS $code
                ON
                    pp.projectid = {$code}.projectid
                    AND pp.pagecode = {$code}.pagecode
                    AND '$code' = {$code}.taskcode";
       } 

       $sql = "
            $sql_select
            $sql_from
            WHERE
                pp.projectid = '$this->_projectid'
            ORDER BY
                pp.pagecode";
        // echo "$sql<br />";

        return $DpDb->SqlRows($sql);
    }

    public function Unzip($zippath) {
        exec("unzip -o -j $zippath -d ".$this->proj_unzip_dir());
    }

    public function PageCount() {
        return $this->_row['pagecount'];
        // return count($this->Pages());
    }

    public function GetOnePage($pagecode) {
        assert(! empty( $pagecode ) ) ;
        return new ProjectPage($this->_projectid, $pagecode) ;
    }

    public function ProjectId() {
        return $this->_projectid;
    }

    public function ProjectPath() {
        $path = PROJECTS_PATH."/$this->_projectid";
        if(! file_exists($path)) {
            mkdir($path, 0777);
            chmod( $path, 0777 ) ;
        }
        file_exists( $path ) 
            or die( "ProjectPath failed: $path" ) ;

        return $path;
    }

    public function Images() {
        require_once "ImageClass.inc";
        return new Images($this->_projectid);
    }

    public function LastPostTime() {
        return $this->_row['post_time'];
    }

    public function PM() {
        return $this->ProjectManager();
    }

    public function SetPM($pm) {
        $this->_row['username'] = $pm;
    }

    public function ProjectManager() {
        return $this->_row['username'];
    }

    public function LastTaskCompletionTime() {
        require_once "DpDateClass.inc";
        $d = new DpDate($this->_row['lasttaskcompletiontime']);
        return $d->PrettyDate();
    }

    public function ImageSource() {
        return $this->_row['image_source'];
    }

    public function SetImageSource($src) {
        $this->_row['image_source'] = $src;
    }

    public function SmoothreadDeadline() {
        return $this->_row['smoothread_deadline'];
    }

    // All the project thumbnails are in a directory
    public function ThumbUrl( $pagecode ) {
        $pg = $this->GetOnePage( $pagecode ) ;
        // require_once "PageClass.inc" ;
        return $this->ProjectPath()."/thumbs"; // name/location of generated thumbnail.
    }

    public function Title() {
        return $this->NameOfWork();
    }

    public function NameOfWork() {
        return $this->_row['nameofwork'];
    }

    public function SetNameOfWork($name) {
        $this->_row['nameofwork'] = $name;
    }

    public function CharTableUrl() {
        $val = $this->_row['chartableurl'];
        if(empty($val)) {
            $val = "chartable.html";
        }
        return $val;
    }

    public function Author() {
        return $this->_row['authorsname'];
    }

    public function AuthorsName() {
        return $this->_row['authorsname'];
    }

    public function SetAuthorsName($author) {
        $this->_row['authorsname'] = $author;
    }

    public function PrimaryLanguageCode() {
        return $this->_row['primary_lang_code'];
    }

    public function Language() {
        return $this->PrimaryLanguageCode() ;
    }

    public function Languages() {
        global $Context;
        $code = $this->SecondaryLanguageCode() ;
        if(! empty( $code ) )
            return $Context->LanguageName( $this->PrimaryLanguageCode() )
                . ", "
                .  $Context->LanguageName( $this->SecondaryLanguageCode() ) ;
        else
            return $Context->LanguageName( $this->PrimaryLanguageCode() ) ;
    }

    public function LanguageCodes() {
        global $Context;
        $code = $this->SecondaryLanguageCode() ;
        if(! empty( $code ) )
            return $this->PrimaryLanguageCode()
                . ", " . $this->SecondaryLanguageCode() ;
        else
            return $this->PrimaryLanguageCode() ;
    }

    public function LanguagesArray() {
        if(! empty($this->_row['secondary_lang_code']))
            return array( $this->PrimaryLanguageCode(), $this->SecondaryLanguageCode() ) ;
        else
            return array( $this->PrimaryLanguageCode() ) ;
    }

    public function SecondaryLanguageCode() {
        return $this->_row['secondary_lang_code'];
    }

    public function SetPrimaryLanguageCode($lang) {
        $this->_row['primary_lang_code'] = $lang;
    }

    public function SetSecondaryLanguageCode($lang) {
        $this->_row['secondary_lang_code'] = $lang;
    }

    public function Clearance() {
        return empty( $this->_row['clearance'] )
            ? "none"
            :  $this->_row['clearance'] ;
    }

    public function SetClearance($clearance) {
        $this->_row['clearance'] = $clearance;
    }

    public function ProjectUrl() {
        return "project.php?projectid=$this->_projectid";
    }

    public function ForumUrl() {
        return "TBD";
    }

    public function NumberPageTasksAvailable() {
        0;
    }

    public function NumberPageTasksCheckedOut() {
        0;
    }

    public function ValidWords() {
        return "";
    }

    public function ExcludeWords() {
        return "";
    }

    /*
       need this layout:
       pagecode task1 task2 task3
       001      array{time  time  time}
     */

    private function PageTaskTimes() {
        static $_rows ;
        if(!isset($_rows))
        {
            $_rows = $this->PageTasks() ;
        }
    }

    public function PageTaskTime($pagecode, $taskcode) {
        $times = $this->PageTaskTimes();
        return $times[$pagecode][$taskcode];
    }

    public function ProjectPageTasks() {
        static $iPgTasks;
        if(!isset($iPgTasks)) {
            require_once "PageTaskClass.inc";
            $iPgTasks = new PageTasks($this->_projectid) ;
        }
        return $iPgTasks ;
    }

    public function PageTasks() {
        static $ipts ;
        if( !isset($ipts ) ) {
            require_once "PageTaskClass.inc";
            $ipts = new PageTasks($this->_projectid) ;
        }
        return $ipts ;
        /*
           global $DpDb;
           $sql = "SELECT
           pt.pagecode,
           pt.taskcode,
           t.description,
           COUNT(*) AS pgcount
           FROM
           pagetasks AS ppt
           JOIN
           projecttasks AS pt
           ON
           pt.projectid = ppt.projectid
           AND pt.taskcode = ppt.taskcode
           LEFT JOIN
           tasks AS t
           ON
           ppt.taskcode = t.taskcode
           WHERE
           ppt.projectid = '$this->_projectid'
           GROUP BY
           pt.pagecode,
           pt.taskcode,
           t.description
           ORDER BY
           pt.pagecode,
           pt.sequencenumber";
           return $DpDb->SqlObjects($sql);
         */
    }

    public function Comments($taskcode = "") {
    /*
        if(! empty( $taskcode ) ) {
            $path = build_path($this->ProjectPath(), $taskcode.".comments.txt") ;
            if( file_exists( $path ) ) {
                return file_read( $path ) ;
            }
        }
        $path = build_path($this->ProjectPath(), "comments.txt") ;
        if( file_exists( $path ) ) {
            return file_read( $path ) ;
        }
        */
        return $this->_row['comments'];
    }

    public function SetComments($comments) {
        $this->_row['comments'] = $comments;
    }

    public function PostedNumber() {
        return $this->_row['postednum'];
    }

    public function SetPostedNumber($num) {
        $this->_row['postednum'] = $num;
    }

    public function Difficulty() {
        return empty( $this->_row['difficulty'] )
            ? "none"
            : $this->_row['difficulty'] ;
    }

    public function Genre() {
        return $this->_row['genre'];
    }

    public function TextPreparer() {
        return $this->_row['text_preparer'];
    }

    public function ImagePreparer() {
        return $this->_row['image_preparer'];
    }

    public function ExtraCredits() {
        return $this->_row['extra_credits'];
    }

    public function SetDifficulty($val) {
        $this->_row['difficulty'] = $val;
    }

    public function SetGenre($val) {
        $this->_row['genre'] = $val;
    }

    public function SetTextPreparer($val) {
        $this->_row['text_preparer'] = $val;
    }

    public function SetImagePreparer($val) {
        $this->_row['image_preparer'] = $val;
    }

    public function SetExtraCredits($val) {
        $this->_row['extra_credits'] = $val;
    }

    public function UserActivePageCount() {
        return $this->_row['my_active_count'] ;
    }

    public function UserSavedPageCount() {
        return $this->_row['my_saved_count'] ;
    }

    public function UserPageCounts2() {
        return $this->UserActivePageCount() . " / " . $this->UserSavedPageCount() ;
    }

    public function UserIsPM() {
        global $User;
        return $this->PM() == $User->UserName() ;
    }

    public function UserMayManage() {
        global $User;
        return $User->MayDoEverything()
            || ($User->_username == $this->PM());
    }

    public function UserMayPostProof() {
        global $User;
        return $User->MayDoAnything()
            || ($User->_username == $this->PM());
    }

    public function Save() {
        if($this->Exists()) {
            $this->Update();
        }
        else {
            $this->SaveNew();
        }
    }

    private function Update() {
        global $DpDb;
        global $User;

        assert(!empty($this->_projectid));

        $sql = "UPDATE
                    projects
                SET
                    nameofwork          = '".SqlEncode($this->NameOfWork())."',
                    authorsname         = '".SqlEncode($this->Author())."',
                    language            = '".$this->PrimaryLanguageCode()."',
                    second_language     = '".$this->SecondaryLanguageCode()."',
                    genre               = '".$this->Genre()."',
                    difficulty          = '".$this->Difficulty()."',
                    clearance           = '".SqlEncode($this->Clearance())."',
                    image_source        = '".SqlEncode($this->ImageSource())."',
                    username            = '{$User->UserName()}'
               WHERE
                   projectid            = '{$this->ProjectId()}'\n";
        // echo "$sql<br />";

        $DpDb->SqlExecute($sql);
    }

    private function SaveNew() {
        global $Context;
        global $User;
        global $DpDb;

        $this->_projectid = $Context->NewProjectId();

        $sql = "INSERT INTO projects
            SET 
                projectid= '$this->_projectid',
                nameofwork      = '".SqlEncode($this->NameOfWork())."',
                authorsname     = '".SqlEncode($this->Author())."',
                language        = '".$this->PrimaryLanguageCode()."',
                second_language = '".$this->SecondaryLanguageCode()."',
                genre           = '".$this->Genre()."',
                difficulty      = '".$this->Difficulty()."',
                clearance       = '".$this->Clearance()."',
                comments        = '".SqlEncode($this->Comments())."',
                image_source    = '".$this->ImageSource()."',
                username        = '".$User->UserName()."'\n";

        $nrows = $DpDb->SqlExecute($sql) ;
        $this->_exists = ( $nrows > 0 );
    }

    public function deleteAllPages() {
        global $DpDb;

        LogProject("DELETE_ALL_PAGES");
        $this->Pages()->DeleteAll();
    }

    /*
    public function AddFilesFrom(&$sets) {
        $this->AddFromFilesets($sets);
    }
    */

    private function set_property($name, $value) {
        $this->_row[$name] = $value;
    }

    // if possible, check out a page for a task. Return the page.
    public function CheckOutNextPage($taskcode) {
        global $DpDb;
        global $User;
        
        $projectid = $this->ProjectId() ;
        $username = $User->UserName() ;

        $sql = "SELECT
                    pt.pagecode 
                FROM 
                    pagetasks pt 

                JOIN
                    tasks t
                ON
                    pt.taskcode = t.taskcode

                LEFT JOIN 
                    userquals uq 
                ON  
                    t.qualcode = uq.qualcode
                    AND uq.username = '$username'

                LEFT JOIN
                    pagetasks AS ptuser
                ON
                    pt.projectid = ptuser.projectid
                    AND pt.pagecode = ptuser.pagecode
                    AND '$username' = ptuser.username

                WHERE
                    pt.projectid = '$projectid'
                    AND pt.taskcode = '$taskcode'
                    AND pt.checkouttime IS NULL

                    -- any higher-priority tasks undone?
                    AND NOT EXISTS (
                        SELECT 1 FROM pagetasks
                        WHERE projectid = pt.projectid
                            AND pagecode = pt.pagecode
                            AND taskcode = pt.taskcode
                            AND sequencenumber < pt.sequencenumber
                            AND completiontime IS NULL
                    )

                    AND ptuser.pagetaskid IS NULL
                    AND (
                        t.tasktype = 'A'
                        OR '$username' NOT IN ( SELECT username FROM userquals
                                             WHERE qualcode = t.qualcode )
                    )

                ORDER BY 
                    pt.pagecode";

        $pagecode = $DpDb->SqlOneValue( $sql );

        if( ! empty( $pagecode )  ) {
            require_once "PageTaskClass.inc" ;
            $pt = new PageTask( $projectid, $pagecode, $taskcode ) ;
            $pt->CheckOut() ;
            return $pt ;
        }
        else
            return null ;
    }


    /*
    function LogEvent($event_type, $details1='', $details2='', $details3='')
    {
        global $User;

        $esc_details1 = sql_pretty($details1);
        $esc_details2 = sql_pretty($details2);
        $esc_details3 = sql_pretty($details3);

        $sql = "INSERT INTO
                    project_events
                SET
                    timestamp  = UNIX_TIMESTAMP(),
                    projectid  = '{$this->ProjectId()}',
                    who        = '{$User->UserName()}',
                    event_type = '$event_type',
                    details1   = '$esc_details1',
                    details2   = '$esc_details2',
                    details3   = '$esc_details3'";
        // echo "$sql<br />";
        $DpDb->SqlExecute($sql) ;
    }
    */
    private function sqlProject() {
        global $User ;
        $username = $User->UserName() ;
        return "SELECT
                    p.projectId,
                    p.username,
                    p.nameofwork,
                    p.authorsname,
                    p.language AS primary_lang_code,
                    p.second_language AS secondary_lang_code,
                    p.genre,
                    p.difficulty,
                    p.image_source,
                    p.clearance,
                    p.postednum,
                    p.comments,
                    p.chartableurl,
                    (   SELECT COUNT(1) FROM pages
                        WHERE projectid = p.projectId
                    ) AS pagecount,
                    (   SELECT COUNT(1) FROM pagetasks
                        WHERE projectid = '{$this->_projectid}'
                            AND username = '$username'
                            AND completiontime IS NULL
                    ) AS my_active_count,
                    (   SELECT COUNT(1) FROM pagetasks
                        WHERE projectid = '{$this->_projectid}'
                            AND username = '$username'
                            AND NOT completiontime IS NULL
                    ) AS my_saved_count
                FROM
                    projects AS p
                    
                WHERE
                    p.projectid = '$this->_projectid'";
                    
    }

    public function ProjectRowPages() {
        static $_pgs;
        global $DpDb;

        if(! isset($_pgs)) {
            $sql = "SELECT
                        pp.pageid,
                        pp.projectid,
                        pp.pagecode,
                        pp.imagefilename,
                        p.nameofwork,
                        p.authorsname
                    FROM
                        pages AS pp
                    JOIN
                        projects AS p
                    ON
                        pp.projectid = p.projectid
                        WHERE
                        pp.projectid = '$this->_projectid'
                    ORDER BY
                        pp.pagecode ";
            $_pgs = $DpDb->SqlObjects( $sql ) ;
        }
        return $_pgs;
    }

    /*
    foreach($rows as $row) {
        $code = $row->pagecode;
        $this->_project_pages[$code] = new RowPage($row) ;
    }
    assert(count($this->_project_pages) == count($this->_rows));

    public function Page($pagecode) {
        assert(! empty( $pagecode ) ) ;
        $pg = @$this->_project_pages[$pagecode];
        return empty( $pg ) ? null : $pg ;
    }
    */

    public function AddFromFilesets(&$sets) {
        foreach($sets as $set) {
            $ipath = $set->ImageFilePath();
            $tpath = $set->TextFilePath();
            if(! empty($ipath) || ! empty($tpath)) {
                $this->AddFromFileset($set);
            }
        }
    }

    private function AddFromFileset( &$set) {
        $projectid      = $this->_projectid ;
        $pagecode       = $set->PageCode();
        $imagename      = $set->ImageFileName();
        // $textpath       = $set->TextFilePath();
        // $imagepath      = $set->NewImagePath();

        // require_once "PageClass.inc";
        // $pg = new ProtoPage($projectid, $pagecode, $imagename);
        if(empty($imagename)) {
            return;
        }
        if(! $set->IsPage()) {
            $set->SetPage( 
                new ProtoPage($projectid, $pagecode, $imagename));
        }
        $set->InitText() ;
        $set->InitImage() ;
        // $pg->InitTextFromPath($textpath);
        // $pg->InitImageFromPath($imagepath);
        // $this->_project_pages[$pagecode] = $pg;
        $this->AddPageRecord($pagecode, $imagename);
    }

    public function AddPageRecord( $pagecode, $imagefilename) {
        global $DpDb;

        $projectid = $this->ProjectId() ;
        $sql = "REPLACE INTO pages
                (   projectid,
                    pagecode,
                    imageFileName
                ) VALUES
                (   '$projectid',
                    '$pagecode',
                    '$imagefilename'
                )";
        // die(PrettySql($sql));
        $i = $DpDb->SqlExecute($sql);
    }

    public function MakeThumbnails() {
        foreach($this->ProjectRowPages() as $pg) {
            $pg->MakeThumbnail(true);
        }
    }
    

}

class ProtoProject extends Project
{
    protected $_exists = false ;

    public function ProtoProject(
            $projectid,
            $nameofwork = '',
            $authorsname = '',
            $primary_lang_code = '',
            $secondary_lang_code = '',
            $genre = '',
            $image_source = 'internal',
            $comments = '',
            $clearance = '',
            $postednum = '',
            $difficulty = '') {
        global $User;
        if(empty($image_preparer))
            $image_preparer = $User->UserName() ;
        if(empty($text_preparer))
            $text_preparer = $User->UserName() ;

        $this->_row['nameofwork']           = $nameofwork;
        $this->_row['authorsname']          = $authorsname;
        $this->_row['primary_lang_code']    = $primary_lang_code;
        $this->_row['secondary_lang_code']  = $secondary_lang_code;
        $this->_row['genre']                = $genre;
        $this->_row['image_source']         = $image_source;
        $this->_row['comments']             = $comments;
        $this->_row['clearance']            = $clearance;
        $this->_row['postednum']            = $postednum;
        $this->_row['difficulty']           = $difficulty;
    }

    public function Exists() {
        return $this->_exists ;
    }

    public function LastPostTime() {
        return 0;
    }
    public function DeleteAll() {
        global $DpDb;

        $sql = "DELETE FROM pages
                WHERE projectId = '{$this->ProjectId()}'";
        $DpDb->SqlExecute($sql);
    }
}

class RowPage extends ProjectPage
{
    protected $_row;
    public function RowPage(&$row) {
        $this->_row = $row ;
        // var_dump($row);
        // $this->_projectid = $row->projectid;
        // $this->_pagecode = $row->pagecode;
        // $this->_row = $row ;
    }

    public function PageCode() {
        return $this->_row->pagecode ;
    }

    public function TaskCode() {
        return $this->_row->taskcode ;
    }
}

?>
